<?php
/**
 * author: draguo
 * Date: 2017/4/26
 */

namespace Admin\Controller;


class ProductController extends BaseController
{
    public function index()
    {
        $list = M('product')->where(['_string' => 'deleted_at is null'])->select();
        $this->list = $list;
        $this->display();
    }

    public function create()
    {
        $this->display();
    }

    public function edit()
    {
        $data = M('product')->find(I('id'));
        $this->data = $data;
        $this->display('create');
    }

    public function store()
    {
        $data = I('post.');
        $data['detail'] = htmlspecialchars_decode($data['editorValue']);
        if ($_FILES['b_logo']['name'] != '') {
            $info = admin_upload();
            if ($info) {
                $data['logo'] = '/uploads/' . $info['b_logo']['savepath'] . $info['b_logo']['savename'];
            }
        }
        $product = M('product');
        $product->startTrans();
        if ($data['product_id']) {
            //编辑图书
            $r = $product->where(['product_id' => $data['product_id']])->save($data);
            if ($r) {
                $product->commit();
                $this->success('修改成功',U('index'));
            } else {
                $product->rollback();
                $this->success('修改失败');
            }
        } else {
            //新增图书
            $r = $product->add($data);
            if ($r) {
                $product->commit();
                $this->success('新增成功','/index/product/index');
            } else {
                $product->rollback();
                $this->success('新增失败');
            }
        }
    }

    public function del()
    {
        $id = I('id');
        $result = M('product')->where(['product_id' => $id])->setField('deleted_at', date('Y-m-d H:i:s'));
        if ($result) {
            $this->success('删除成功');
        } else {
            $this->success('删除失败');
        }

    }

    public function exchangeHistory()
    {
        $data = M('order_has_product')->alias('a')->join('user on user.user_id = a.user_id')
            ->join('product on product.product_id = a.product_id')->order('a.create_time desc')->select();
        $this->list = $data;
        $this->display();
    }
}